import React, { useEffect } from 'react'
import _ from 'lodash';
import { connect } from 'react-redux'
import { Dispatch, bindActionCreators } from 'redux'
import { RootState } from 'src/redux'
//ui
import { Tree, Row, Col, Button, Modal, Input, Card } from 'antd';
import { DeleteOutlined, PlusOutlined, EditOutlined } from '@ant-design/icons';
//ds
import { Key } from 'rc-tree/lib/interface';
//state
import { WordSourceState } from './reducer';
//action
import * as Action from './reducer'
import * as MainInfo from '../MainInfo/reducer'

export interface WordSourceProps {
    state: WordSourceState;
    /**
     * 根据数字转换来的选择表
     */
    selectedKeys?: Key[];

    onFetch: typeof Action.fetch;
    onNodeDelete: typeof Action.remove;
    onNodeAdd: typeof Action.add;
    onNodeEdit: typeof Action.edit;
    mainInfoSetWordSourceId: typeof MainInfo.setWordSourceId;

    setCurrentIdInner: typeof Action.setCurrentIdInner
    setCurrentId: typeof Action.setCurrentId
    outerSettedId?: number;
}


export const _WordSource: React.FC<WordSourceProps> = (props) => {
    const { confirm } = Modal;
    const {
        state,
        outerSettedId,
        onFetch, onNodeDelete, onNodeAdd, onNodeEdit,
        setCurrentIdInner, setCurrentId,
        mainInfoSetWordSourceId,
    } = props;

    const [addModelVisible, setAddModelVisible] = React.useState(false);
    const [editModelVisible, setEditModelVisible] = React.useState(false);
    const [addModelValue, setAddModelValue] = React.useState("");
    const [editModelValue, setEditModelValue] = React.useState("");
    //对外选择节点号
    const [wordSourceId, setWordSourceId] = React.useState<number | null>(null);
    //对内选择的key，tree的可控属性
    const [selectedKeys, setSelectedKeys] = React.useState<string[]>([]);

    const keysToKey = (keys: string[]) => (_.isEmpty(keys)) ? (null) : (Number.parseInt(keys[0].toString().substring(1)))
    const keyToKeys = (key: string) => [key]

    //初始化source树
    useEffect(() => {
        onFetch();
    }, [onFetch]);

    // //select第一步触发
    // useEffect(() => {
    //     //内部selectedKeys转外部wordSourceId
    //     const newId = keysToKey(selectedKeys)
    //     setWordSourceId(newId)
    //     if (!_.isNull(newId)) {
    //         if (outerSettedId) {
    //             setCurrentIdInner(newId)
    //         }
    //         else {
    //             setCurrentId(newId)
    //         }
    //     }

    // }, [outerSettedId, selectedKeys, setCurrentId, setCurrentIdInner]);

    //外部影响内部选择
    useEffect(() => {
        //myinner -> sourceinner
        let key = ""
        if (outerSettedId) {
            key = 't' + outerSettedId.toString()
        }
        else {
            key = state.dto.key.toString()
        }
        setSelectedKeys(keyToKeys(key))
    }, [outerSettedId, state.dto.key])

    //传递到另一个redux state
    useEffect(() => {
        mainInfoSetWordSourceId(state.currentId)
    }, [mainInfoSetWordSourceId, state.currentId]);

    const onBtn = {
        select: (e: Key[]) => {
            const keys = e.map(e => e.toString())
            setSelectedKeys(keys)
            const key = keysToKey(keys)
            setWordSourceId(key)
            if (!_.isNull(key)) {
                if (outerSettedId) {
                    setCurrentIdInner(key)
                }
                else {
                    setCurrentId(key)
                }
            }
        },
        add: () => setAddModelVisible(true),
        edit: () => setEditModelVisible(true),
        remove: () => confirm({
            title: '你确定要删除节点吗',
            content: '？？？',
            okText: '是的',
            okType: 'default',
            cancelText: '不',
            onOk() {
                if (_.isNull(wordSourceId)) {
                    confirm({
                        title: '警告',
                        content: "请选择例句来源"
                    });
                }
                else {
                    onNodeDelete({ wordSourceId, wordSourceValue: "" })
                    setAddModelVisible(false);
                }
            }
        }),
    }

    const onNode = {
        add: () => {
            if (_.isNull(wordSourceId)) {
                confirm({
                    title: '警告',
                    content: "请选择例句来源"
                });
            }
            else {
                onNodeAdd({ wordSourceId, wordSourceValue: addModelValue });
                setAddModelVisible(false);
            }
        },
        edit: () => {
            if (_.isNull(wordSourceId)) {
                confirm({
                    title: '警告',
                    content: "请选择例句来源"
                });
            }
            else {
                onNodeEdit({ wordSourceId, wordSourceValue: editModelValue });
                setEditModelVisible(false);
            }
        }
    }


    return (<div>
        {/* 这是森林[]！！！！ */}
        <Card
            title='来源树'
        >
            <Tree
                showLine={true}
                style={{ padding: "1em" }}
                treeData={[state.dto]}
                selectedKeys={selectedKeys}
                defaultExpandAll
                onSelect={onBtn.select}
            >
            </Tree>
            <Card
                size="small"
            >
                <Row style={{ textAlign: "center" }}>
                    <Col span={8}><Button onClick={onBtn.add} icon={<PlusOutlined />}></Button></Col>
                    <Col span={8}><Button onClick={onBtn.edit} icon={<EditOutlined />}></Button></Col>
                    <Col span={8}><Button onClick={onBtn.remove} icon={<DeleteOutlined />}></Button></Col>
                </Row>
            </Card>

            <Modal
                title="添加子节点"
                visible={addModelVisible}
                onCancel={() => setAddModelVisible(false)}
                onOk={onNode.add}
            >
                <Input value={addModelValue} onChange={(e) => setAddModelValue(e.target.value)}></Input>
            </Modal>

            <Modal
                title="修改子节点"
                visible={editModelVisible}
                onCancel={() => setEditModelVisible(false)}
                onOk={onNode.edit}
            >
                <Input value={editModelValue} onChange={(e) => setEditModelValue(e.target.value)}></Input>
            </Modal>
        </Card>
    </div>);
}




const mapStateToProps = (state: RootState) => ({
    state: state.WordSourceState,
})

const mapDispatchToProps = (dispatch: Dispatch) =>
    bindActionCreators({
        onFetch: Action.fetch,
        onNodeAdd: Action.add,
        onNodeEdit: Action.edit,
        onNodeDelete: Action.remove,
        setCurrentIdInner: Action.setCurrentIdInner,
        setCurrentId: Action.setCurrentId,
        mainInfoSetWordSourceId: MainInfo.setWordSourceId,
    }, dispatch)


/**
 * 得到当前过滤器并渲染 Link。
 */
const WordSource = connect(
    mapStateToProps,
    mapDispatchToProps
)(_WordSource)

export default WordSource